/**
 * @Description: 百度离线地图
 * @Author: xubaoliang
 * @Date: 2022-01-25 09:19:27
 */
import TileGrid from "ol/tilegrid/TileGrid";
import TileImage from "ol/source/TileImage";
import TileLayer from "ol/layer/Tile";
import BMapStyle from "../theme/bmap";
import {addCoordinateTransforms, addProjection, Projection} from "ol/proj";
import gcoord from "gcoord";
import {Map, View} from "ol";
import dayjs from "dayjs";

let BMap = {
  /**
   * 初始化百度地图
   * @param elId
   * @param configs
   * @param options
   * @return {Map}
   */
  init: function (elId, configs, options) {
    let projBD09 = new Projection({
      code: 'BD:09',
      extent: [-20037726.37, -11708041.66, 20037726.37, 12474104.17],
      units: 'm',
      axisOrientation: 'neu',
      global: false
    });
    addProjection(projBD09);
    addCoordinateTransforms("EPSG:4326", "BD:09",
      function (coordinate) {
        return gcoord.transform(coordinate, gcoord.WGS84, gcoord.BD09Meter);
      },
      function (coordinate) {
        return gcoord.transform(coordinate, gcoord.BD09Meter, gcoord.WGS84);
      }
    );
    let resolutions = [];
    for (let i = 0; i < 19; i++) {
      resolutions[i] = Math.pow(2, 18 - i);
    }
    let tileGrid = new TileGrid({
      origin: [0, 0],
      resolutions: resolutions,
      tileSize:[256, 256],
      zDirection: 1
    });
    let tileSource = new TileImage({
      projection: "BD:09",
      tileGrid: tileGrid,
      tilePixelRatio: 1,
      crossOrigin: 'anonymous',
      tileUrlFunction: function (tileCoord) {
        if (!tileCoord) {
          return "";
        }
        let z = tileCoord[0];
        let x = tileCoord[1];
        let y = -tileCoord[2] - 1;
        if (x < 0) {
          x = "M" + (-x).toString();
        }
        if (y < 0) {
          y = "M" + (-y).toString();
        }
        if(configs.mapType.toLowerCase() === 'bmap') {
          if (!configs.mapStyle || configs.mapStyle === '') {
            return process.env.VUE_APP_MAP_TILE + "/" + z + "/" + x + "/" + y + ".png";
          } else {
            return process.env.VUE_APP_MAP_TILE + "/" + BMapStyle[configs.mapStyle] + "/" + z + "/" + x + "/" + y + ".png";
          }
        }
        else {
          let urlNum = (Math.abs(x + y) % 4).toString();
          if (!configs.mapStyle || configs.mapStyle === '') {
            return "http://maponline" + urlNum + ".bdimg.com/tile/?qt=vtile&x=" + x + "&y=" + y + "&z=" + z;
          } else {
            return "http://mapapip0.bdimg.com/customimage/tile?qt=customimage&x=" + x + "&y=" + y + "&z=" + z
              + "&customid=" + BMapStyle[configs.mapStyle] + '&ak=' + configs.mapKey + "&udt=" + dayjs().format("YYYY-MM-DD");
          }
        }
      }
    });
    let mapLayer = new TileLayer({
      id: 'baseLayer',
      source: tileSource,
    });
    let mapApp = new Map({
      target: elId,
      layers: [mapLayer],
      view: new View({
        // projection: 'EPSG:4326',    //使用这个坐标系
        projection: 'BD:09',
        center: gcoord.transform(options.center || configs.mapCenter, gcoord.WGS84, gcoord.BD09Meter),
        zoom: options.zoom || configs.defaultZoom,
        minZoom: options.minZoom || configs.minZoom,
        maxZoom: options.maxZoom || configs.maxZoom,
        // 设置缩放级别为整数
        constrainResolution: true,
        // 关闭无级别缩放地图
        smoothResolutionConstraint: false,
        // aaa
        resolutions: resolutions,
      }),
      controls: []
    });
    return mapApp;
  },
  /**
   * 实时路况
   * @return {TileLayer<TileSourceType>}
   */
  addTrafficLayer() {
    let resolutions = [];
    for (let i = 0; i < 19; i++) {
      resolutions[i] = Math.pow(2, 18 - i);
    }
    let tileGrid = new TileGrid({
      origin: [0, 0],
      resolutions: resolutions
    });
    let trafficSource = new TileImage({
      projection: 'BD:09', //'EPSG:3857',
      tileGrid: tileGrid,
      crossOrigin: 'anonymous',
      tileUrlFunction: function (tileCoord) {
        if (!tileCoord) {
          return "";
        }
        let z = tileCoord[0];
        let x = tileCoord[1];
        let y = -tileCoord[2] - 1;
        if (x < 0) {
          x = "M" + (-x).toString();
        }
        if (y < 0) {
          y = "M" + (-y).toString();
        }
        let time = Date.now() * 1000 + 81;
        return `https://traffic.map.baidu.com/traffic/TrafficTileService?level=${z}&x=${x}&y=${y}&time=${time}&smallflow=1&scaler=1`;
      }
    });
    let trafficLayer = new TileLayer({
      id: 'trafficLayer',
      source: trafficSource
    });

    return trafficLayer;
  },
  /**
   * 实时路况预测
   * @param day
   * @param hour
   * @return {TileLayer<TileSourceType>}
   */
  addHistoryTrafficLayer(day, hour) {
    if(!day) {
      day = 1;
    }
    if(!hour) {
      hour = 10;
    }
    let resolutions = [];
    for (let i = 0; i < 19; i++) {
      resolutions[i] = Math.pow(2, 18 - i);
    }
    let tileGrid = new TileGrid({
      origin: [0, 0],
      resolutions: resolutions
    });
    let trafficSource = new TileImage({
      projection: 'BD:09', //'EPSG:3857',
      tileGrid: tileGrid,
      crossOrigin: 'anonymous',
      tileUrlFunction: function (tileCoord) {
        if (!tileCoord) {
          return "";
        }
        let z = tileCoord[0];
        let x = tileCoord[1];
        let y = -tileCoord[2] - 1;
        if (x < 0) {
          x = "M" + (-x).toString();
        }
        if (y < 0) {
          y = "M" + (-y).toString();
        }
        let time = Date.now() * 1000 + 81;
        return `https://traffic.map.baidu.com/traffic/HistoryService?level=${z}&x=${x}&y=${y}&day=${day}&hour=${hour}&time=${time}&smallflow=1&scaler=1`;
      }
    });
    let trafficLayer = new TileLayer({
      id: 'historyTrafficLayer',
      source: trafficSource
    });

    return trafficLayer;
  }
}

export default BMap;
